import { get, post, put, del } from '@/utils/request'
import type { Role } from './system.service'

export interface User {
  id: string
  username: string
  roles: Role[]
  status: 'active' | 'locked' | 'disabled'
  lastLoginTime: string
  lastLoginIp: string
  createdAt: string
}

export interface UserParams {
  username?: string
  role?: string
  status?: string
  startTime?: string
  endTime?: string
  page: number
  pageSize: number
}

export interface CreateUserParams {
  username: string
  password: string
  status: string
}

export interface UpdateUserParams {
  username?: string
  status?: string
}

const UserAPI = {
  list: '/api/users',
  create: '/api/users',
  update: (id: string) => `/api/users/${id}`,
  delete: (id: string) => `/api/users/${id}`,
  roles: {
    list: '/api/users/roles',
    update: (id: string) => `/api/users/${id}/roles`,
  },
}

export const UserService = {
  async getUsers(params: UserParams) {
    return get<{ total: number; items: User[] }>(UserAPI.list, params)
  },

  async createUser(params: CreateUserParams) {
    return post<User>(UserAPI.create, params)
  },

  async updateUser(id: string, params: UpdateUserParams) {
    return put<User>(UserAPI.update(id), params)
  },

  async deleteUser(id: string) {
    return del(UserAPI.delete(id))
  },

  async getRoles() {
    return get<Role[]>(UserAPI.roles.list)
  },

  async updateUserRoles(id: string, roles: string[]) {
    return put(UserAPI.roles.update(id), { roles })
  },
}
